package org.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MappingConfigPanel extends JPanel {
    private static final Log log = LogFactory.getLog(MappingConfigPanel.class);
    private String excelFilePath;
    private ConfigPersistenceService configPersistence;
    private ExcelReader excelReader;
    private JComboBox<String> targetTableComboBox = new JComboBox<>();
    private Map<String, List<String>> tableColumnsMap = new HashMap<>();
    private List<String> excelHeaders = new ArrayList<>();
    private MappingRuleDAO mappingRuleDAO;
    private JComboBox<String> tableComboBox;  // 目标表选择框
    private JPanel rulesPanel;
    private List<MappingRule> rules = new ArrayList<>();
    private List<String> allTables = new ArrayList<>();
    private ExecutorService migrationExecutor = Executors.newSingleThreadExecutor();
    private JComboBox<String> sheetComboBox;  // 新增的sheet选择框
    private List<String> sheetNames = new ArrayList<>();  // 存储sheet名称列表
    private String sheetName = "接触的危害因素";


    public MappingConfigPanel(ConfigPersistenceService configPersistence, ExcelReader excelReader, MappingRuleDAO mappingRuleDAO) {
        this.configPersistence = configPersistence;
        this.excelReader = excelReader;
        this.mappingRuleDAO = mappingRuleDAO;
        initUI();
        loadDatabaseTables();
    }

    @SneakyThrows
    private void initUI() {
        setLayout(new BorderLayout());

        // 表选择和文件选择面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        // 文件选择按钮
        JButton fileButton = new JButton("选择Excel文件");
        fileButton.addActionListener(e -> selectExcelFile());

        // 目标表选择
        JLabel tableLabel = new JLabel("目标表:");
        targetTableComboBox.addActionListener(e -> {
            try {
                loadSelectedTableColumns();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });

        // 新增的sheet选择框
        sheetComboBox = new JComboBox<>();
        sheetComboBox.addActionListener(e -> {
            // 当sheet选择改变时更新Excel头信息
            updateExcelHeaders();
        });

        // 添加组件到顶部面板
        topPanel.add(fileButton);
        topPanel.add(tableLabel);
        topPanel.add(targetTableComboBox);
        topPanel.add(sheetComboBox);
        // 添加到主面板
        add(topPanel, BorderLayout.NORTH);

        // 规则列表面板
        rulesPanel = new JPanel();
        rulesPanel.setLayout(new BoxLayout(rulesPanel, BoxLayout.Y_AXIS));
        JScrollPane scrollPane = new JScrollPane(rulesPanel);
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addButton = new JButton("添加映射");
        JButton saveButton = new JButton("保存配置");
        JButton migrationButton = new JButton("开始迁移");

        addButton.addActionListener(this::addMappingRule);
        saveButton.addActionListener(this::saveRules);
        migrationButton.addActionListener(this::task);

        buttonPanel.add(addButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(migrationButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void task(ActionEvent event) {
        log.info("开始迁移数据...第一步");

        // 创建并配置迁移任务
        MigrationTask migrationTask = new MigrationTask(
                targetTableComboBox.getSelectedItem().toString()
        );

        migrationTask.run();
        JOptionPane.showMessageDialog(this, "数据迁移完成", "成功", JOptionPane.INFORMATION_MESSAGE);

    }


    private class MigrationTask implements Runnable {
        private String targetTableName;
        private int totalRecords;
        private Exception error;
        private boolean done = false;

        public MigrationTask(String targetTableName) {
            this.targetTableName = targetTableName;
        }

        @Override
        public void run() {
            try {
                log.info("开始迁移数据...");
                // 1. 读取Excel数据
                List<MappingRule> rules = configPersistence.getDbManager().getMappingRulesByTargetTable(targetTableName);

                List<Map<String, Object>> rawData = excelReader.readExcel(new File(rules.get(0).getFilePath()), sheetName);
                totalRecords = rawData.size();

                // 2. 获取映射规则

                // 3. 应用映射规则转换数据
                List<Map<String, Object>> transformedData = new DataTransformationService(configPersistence.getDbManager()).transformData(rawData, rules);


                // 5. 批量插入数据（分批处理）
                int batchSize = 500;

                List<List<Map<String, Object>>> splitList = splitList(transformedData, batchSize);
                for (List<Map<String, Object>> batch : splitList) {
                    configPersistence.getDbManager().batchInsert(targetTableName, batch);
                    updateProgress(batch.size());
                }
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                error = ex;
//                progressMonitor.migrationFailed(ex.getMessage());
            } finally {
                done = true;
            }
        }

        public static List<List<Map<String, Object>>> splitList(List<Map<String, Object>> list, int chunkSize) {
            if (list == null) {
                throw new IllegalArgumentException("原始列表不能为空");
            }
            if (chunkSize <= 0) {
                throw new IllegalArgumentException("拆分大小必须大于0");
            }

            List<List<Map<String, Object>>> result = new ArrayList<>();
            for (int i = 0; i < list.size(); i += chunkSize) {
                int end = Math.min(i + chunkSize, list.size());
                result.add(new ArrayList<>(list.subList(i, end)));
            }
            return result;
        }

        private void updateProgress(int recordsProcessed) {
//            progressMonitor.updateProgress(recordsProcessed);
        }

        public boolean isDone() {
            return done;
        }

        public boolean hasError() {
            return error != null;
        }

        public Exception getError() {
            return error;
        }

        public int getTotalRecords() {
            return totalRecords;
        }
    }

    private String getSqlType(String javaType) {
        switch (javaType) {
            case "Integer":
                return "INT";
            case "Long":
                return "BIGINT";
            case "Double":
            case "BigDecimal":
                return "DECIMAL(19,4)";
            case "LocalDate":
            case "LocalDateTime":
                return "DATETIME";
            default:
                return "VARCHAR(255)";
        }
    }


    private void selectExcelFile() {
        Workbook workbook = null;
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileNameExtensionFilter("Excel Files", "xls", "xlsx"));
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                // 读取Excel文件并获取表头
                excelFilePath = file.getPath();
                workbook = WorkbookFactory.create(file);
                sheetNames.clear();
                for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                    sheetNames.add(workbook.getSheetName(i));
                }
                sheetComboBox.removeAllItems();
                for (String sheetName : sheetNames) {
                    sheetComboBox.addItem(sheetName);
                }
                if (!sheetNames.isEmpty()) {
                    sheetComboBox.setSelectedIndex(0);
                    // 读取第一个sheet的表头
                    updateExcelHeaders();
                }

                // 清除现有规则
                rulesPanel.removeAll();

                // 如果已选择目标表，重新加载字段映射
                if (targetTableComboBox.getSelectedItem() != null) {
                    String selectedTable = (String) targetTableComboBox.getSelectedItem();
                    loadTableColumns(selectedTable);
                }

                rulesPanel.revalidate();
                rulesPanel.repaint();

                // 保存到最近文件记录
                //configPersistence.saveRecentFile(file.getAbsolutePath());

            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "文件读取错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "未知错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                try {
                    if (workbook != null) {
                        workbook.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    private void updateEnumMappingButtonState() {
//        // 只有在枚举类型时才启用枚举映射按钮
//        Object selectedItem = conversionTypeComboBox.getSelectedItem();
//        if (selectedItem == null) {
//            enumMappingButton.setEnabled(false);
//            return;
//        }
//
//        boolean isEnum = !selectedItem.toString().equals("String");
//        enumMappingButton.setEnabled(isEnum);
//    }


    // 枚举映射对话框类
    private static class EnumMappingDialog extends JDialog {
        private final JTextField[][] mappingFields;
        private boolean confirmed = false;
        private final int maxMappings = 10;
        private final JPanel panel;
        private ObjectMapper objectMapper = new ObjectMapper(); // 用于JSON序列化

        @SneakyThrows
        public EnumMappingDialog(Frame owner, String title, boolean modal, String initialMapping) {
            super(owner, title, modal);
            panel = new JPanel(new GridLayout(0, 2, 5, 5));
            mappingFields = new JTextField[maxMappings][2];

            // 解析初始映射字符串
            Map<String, String> mappings = new HashMap<>();
            if (initialMapping != null && !initialMapping.isEmpty()) {
                HashMap jsonMap = objectMapper.readValue(initialMapping, HashMap.class);
                mappings.putAll(jsonMap);
            }

            // 创建映射输入字段
            for (int i = 0; i < maxMappings; i++) {
                JTextField oldField = new JTextField();
                JTextField newField = new JTextField();
                if (i < mappings.size()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) mappings.entrySet().toArray()[i];
                    oldField.setText(entry.getKey());
                    newField.setText(entry.getValue());
                }
                mappingFields[i][0] = oldField;
                mappingFields[i][1] = newField;
                panel.add(new JLabel("旧值:"));
                panel.add(oldField);
                panel.add(new JLabel("新值:"));
                panel.add(newField);
            }

            JButton confirmButton = new JButton("确定");
            JButton cancelButton = new JButton("取消");

            confirmButton.addActionListener(e -> {
                confirmed = true;
                dispose();
            });

            cancelButton.addActionListener(e -> dispose());

            JPanel buttonPanel = new JPanel();
            buttonPanel.add(confirmButton);
            buttonPanel.add(cancelButton);

            add(panel, BorderLayout.CENTER);
            add(buttonPanel, BorderLayout.SOUTH);
            pack();
            setLocationRelativeTo(owner);
        }

        public boolean isConfirmed() {
            return confirmed;
        }

        @SneakyThrows
        public String getMappingString() {
            // 创建JSON对象
            Map<String, String> mappingMap = new HashMap<>();

            for (int i = 0; i < maxMappings; i++) {
                String oldVal = mappingFields[i][0].getText().trim();
                String newVal = mappingFields[i][1].getText().trim();
                if (!oldVal.isEmpty() && !newVal.isEmpty()) {
                    mappingMap.put(oldVal, newVal);
                }
            }

            // 转换为JSON字符串
            return objectMapper.writeValueAsString(mappingMap);
        }
    }


    private void updateExcelHeaders() {
        String selectedSheet = (String) sheetComboBox.getSelectedItem();
        sheetName = selectedSheet;
        if (selectedSheet != null && !selectedSheet.isEmpty()) {
            try {
                Workbook workbook = WorkbookFactory.create(new File(excelFilePath));
                Sheet sheet = workbook.getSheet(selectedSheet);
                if (sheet != null) {
                    Row headerRow = sheet.getRow(0);
                    excelHeaders.clear();
                    for (Cell cell : headerRow) {
                        String header = cell.getStringCellValue();
                        excelHeaders.add(header);
                    }
                }
                // 更新现有规则的源字段下拉框
                for (Component comp : rulesPanel.getComponents()) {
                    if (comp instanceof MappingRuleComponent) {
                        JComboBox<String> sourceFieldComboBox = ((MappingRuleComponent) comp).sourceFieldComboBox;
                        sourceFieldComboBox.removeAllItems();
                        for (String excelHeader : excelHeaders) {
                            sourceFieldComboBox.addItem(excelHeader);
                        }
                    }
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "读取Excel表头失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void loadDatabaseTables() {
        try {
            allTables = configPersistence.getAllTables().stream().distinct().toList();
            for (String table : allTables) {
                targetTableComboBox.addItem(table);
            }
            if (!allTables.isEmpty()) {
                String selectedTable = allTables.get(0);
                targetTableComboBox.setSelectedItem(selectedTable);
                loadTableColumns(selectedTable);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据库表失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadSelectedTableColumns() throws SQLException {
        String selectedTable = (String) targetTableComboBox.getSelectedItem();
        if (selectedTable != null) {
            // 更新现有规则以匹配新选择的目标表字段
            loadTableColumns(selectedTable);
            //updateExistingRulesWithNewColumns();
        }
    }

    private void loadTableColumns(String tableName) {
        try {
            // 修改getTableColumns方法调用，获取字段和类型映射
            Map<String, String> columnsWithTypes = configPersistence.getTableColumnsWithTypes(tableName);
            List<String> list = new ArrayList<>(columnsWithTypes.keySet());
            tableColumnsMap.put(tableName, list);

            // 存储字段类型信息
            Map<String, String> typeMap = new HashMap<>();
            for (Map.Entry<String, String> entry : columnsWithTypes.entrySet()) {
                typeMap.put(entry.getKey(), entry.getValue());
            }

            // 清除现有规则
            rulesPanel.removeAll();
            rules.clear();

            // 尝试从数据库加载已有的配置
            List<MappingRule> savedRules = configPersistence.getMappingRulesByTargetTable(tableName);

            // 如果有保存的配置，使用保存的配置
            if (!savedRules.isEmpty()) {
                for (MappingRule rule : savedRules) {
                    // 确保字段类型信息正确
//                    if (typeMap.containsKey(rule.getTargetField())) {
//                        rule.setConversionType(typeMap.get(rule.getTargetField()));
//                        rule.setTargetType(typeMap.get(rule.getTargetField()));
//                    }
//                    rule.setTargetTable(tableName);
                    addRuleComponent(rule);
                }
            } else {
                // 否则自动添加目标表字段
                for (String column : list) {
                    MappingRule rule = new MappingRule();
                    rule.setTargetField(column);
                    // 设置字段类型
                    if (typeMap.containsKey(column)) {
                        rule.setConversionType(typeMap.get(rule.getTargetField()));
                        rule.setTargetType(typeMap.get(column));
                    }
                    // 设置目标表名
                    rule.setTargetTable(tableName);
                    addRuleComponent(rule);
                }
            }

            // 刷新界面
            rulesPanel.revalidate();
            rulesPanel.repaint();

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载表字段失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 更新现有规则以匹配新选择的目标表字段
     */
//    private void updateExistingRulesWithNewColumns() throws SQLException {
//        String selectedTable = (String) targetTableComboBox.getSelectedItem();
//        if (selectedTable == null) return;
//
//        // 获取新表的字段
//        List<String> newColumns = tableColumnsMap.get(selectedTable);
//        //if (newColumns == null || newColumns.isEmpty()) return;
//
//        // 清除现有规则
//        rulesPanel.removeAll();
//        rules.clear();
//
//        // 使用Map来存储字段和类型的映射
//        Map<String, String> columnTypeMap = new HashMap<>();
//
//        // 获取字段类型信息
//        try {
//            columnTypeMap = configPersistence.getTableColumnsWithTypes(selectedTable);
//        } catch (SQLException e) {
//            JOptionPane.showMessageDialog(this, "获取字段类型失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
//        }
//
//        // 尝试从数据库加载已有的配置
//        List<MappingRule> savedRules = configPersistence.getMappingRulesByTargetTable(selectedTable);
//
//        // 如果有保存的配置，使用保存的配置
//        if (!savedRules.isEmpty()) {
//            for (MappingRule rule : savedRules) {
//                // 确保字段类型信息正确
//                if (columnTypeMap.containsKey(rule.getTargetField())) {
//                    rule.setTargetType(columnTypeMap.get(rule.getTargetField()));
//                    rule.setConversionType(columnTypeMap.get(rule.getTargetField()));
//                }
//                rule.setTargetTable(selectedTable);
//                addRuleComponent(rule);
//            }
//        } else {
//            // 否则自动添加目标表字段
//            // 使用Set来避免重复字段
//            Set<String> addedFields = new HashSet<>();
//
//
//
//            // 为每个新字段创建规则
//            for (String column : newColumns) {
//                // 跳过已添加的字段
//                if (addedFields.contains(column)) {
//                    continue;
//                }
//
//                MappingRule rule = new MappingRule();
//                rule.setTargetField(column);
//                // 设置字段类型
//                if (columnTypeMap.containsKey(column)) {
//                    rule.setConversionType(columnTypeMap.get(column));
//                    rule.setTargetType(columnTypeMap.get(column));
//                }
//                // 设置目标表名
//                rule.setTargetTable(selectedTable);
//                addRuleComponent(rule);
//                addedFields.add(column);
//            }
//        }
//
//        // 刷新界面
//        rulesPanel.revalidate();
//        rulesPanel.repaint();
//    }
    private void addMappingRule(ActionEvent event) {
        MappingRule newRule = new MappingRule();
        newRule.setConversionType("String");
        // 默认情况下，目标字段为空
        newRule.setTargetField("");

        addRuleComponent(newRule);
        rulesPanel.revalidate();
        rulesPanel.repaint();
    }

    private void addRuleComponent(MappingRule rule) {
        MappingRuleComponent ruleComponent = new MappingRuleComponent(rule, excelHeaders);
        rulesPanel.add(ruleComponent);
        rulesPanel.add(Box.createVerticalStrut(5)); // 添加间距
    }

    private void saveRules(ActionEvent event) {
        // 收集界面中的规则
        List<MappingRule> updatedRules = new ArrayList<>();
        for (Component comp : rulesPanel.getComponents()) {
            if (comp instanceof MappingRuleComponent) {
                String selectedItem = targetTableComboBox.getSelectedItem().toString();
                MappingRule mappingRule = ((MappingRuleComponent) comp).getMappingRule();
                mappingRule.setTargetTable(selectedItem);
                mappingRule.setFilePath(excelFilePath);
                updatedRules.add(mappingRule);
            }
        }

        // 保存到数据库
        try {
            // 先清除旧规则
            mappingRuleDAO.createTable(); // 确保表存在
            mappingRuleDAO.deleteRulesByName(updatedRules.get(0).getTargetTable());
            // 重新插入新规则
            for (MappingRule rule : updatedRules) {
                mappingRuleDAO.saveRule(rule);
            }
            JOptionPane.showMessageDialog(this, "映射规则保存成功！", "信息", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存映射规则失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    private void createUIComponents() {
        // 创建目标表选择框
        tableComboBox = new JComboBox<>();
        tableComboBox.setPreferredSize(new Dimension(200, 25));

        // 添加表选择监听器
        tableComboBox.addActionListener(e -> {
            String selectedTable = (String) tableComboBox.getSelectedItem();
            if (selectedTable != null) {
                loadTableColumns(selectedTable);
            }
        });

        // 初始化表列表
        try {
            List<String> tables = configPersistence.getAllTables();
            for (String table : tables) {
                tableComboBox.addItem(table);
            }

            // 如果有默认表，加载它
            if (!tables.isEmpty()) {
                tableComboBox.setSelectedIndex(0);
                loadTableColumns(tables.get(0));
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载表列表失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    // 在MappingConfigPanel内部定义MappingRuleComponent类
    private class MappingRuleComponent extends JPanel {
        private JComboBox<String> sourceFieldComboBox;
        private JTextField targetField;
        private JComboBox<String> conversionTypeComboBox;
        private JButton enumMappingButton;
        private JTextField dateFormatField;
        private JTextField fkTableField;
        private JTextField fkColumnField;
        private JTextField defaultValueField;  // 新增：默认值输入框
        // 添加外键目标字段输入框
        private JTextField fkTargetColumnField;
        private JLabel targetTypeLabel;
        private JComboBox<String> relationTableComboBox;
        private JComboBox<String> relationColumnComboBox;
        private JComboBox<String> targetColumnComboBox;
        private String enumMappingValue;

        public MappingRuleComponent(MappingRule rule, List<String> excelHeaders) {
            initUI(rule, excelHeaders);
        }

        private void initUI(MappingRule rule, List<String> excelHeaders) {
            setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));

            // 源字段下拉框
            JLabel sourceLabel = new JLabel("Excel列名:");
            sourceFieldComboBox = new JComboBox<>();
            for (String header : excelHeaders) {
                sourceFieldComboBox.addItem(header);
            }

            // 目标字段输入框
            JLabel targetLabel = new JLabel("目标字段:");
            targetField = new JTextField(15);

            // 添加目标字段类型标签
            targetTypeLabel = new JLabel();
            targetTypeLabel.setPreferredSize(new Dimension(100, 25));

            // 转换类型下拉框
            JLabel typeLabel = new JLabel("类型:");
            conversionTypeComboBox = new JComboBox<>(new String[]{
                    "Integer", "Long", "Double", "BigDecimal", "LocalDate", "LocalDateTime", "String"
            });

            // 枚举映射按钮
            enumMappingButton = new JButton("枚举映射");

            // 新增：默认值输入框
            JLabel defaultLabel = new JLabel("默认值:");
            defaultValueField = new JTextField(15);

            // 日期格式输入框
            JLabel dateFormatLabel = new JLabel("日期格式:");
            dateFormatField = new JTextField(10);

            // 外键配置
            JLabel fkTableLabel = new JLabel("外键表:");
            relationTableComboBox = new JComboBox<>();
            if (allTables.isEmpty()) {
                try {
                    allTables = configPersistence.getAllTables();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            relationTableComboBox.addItem(null);
            for (String allTable : allTables) {
                relationTableComboBox.addItem(allTable);
            }

            //fkTableField = new JTextField(10);
            JLabel fkColumnLabel = new JLabel("列:");
            relationColumnComboBox = new JComboBox<>();
            targetColumnComboBox = new JComboBox<>();
            relationTableComboBox.addActionListener(e -> {
                String selectedItem = (String) relationTableComboBox.getSelectedItem();
                if (selectedItem != null) {
                    try {
                        List<String> columns = tableColumnsMap.get(selectedItem);
                        if (columns == null) {
                            columns = configPersistence.getTableColumns(selectedItem).stream().distinct().toList();
                            tableColumnsMap.put(selectedItem, columns);
                        }
                        relationColumnComboBox.addItem(null);
                        targetColumnComboBox.addItem(null);

                        for (String allTable : columns) {
                            relationColumnComboBox.addItem(allTable);
                            targetColumnComboBox.addItem(allTable);
                        }

                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                }

            });
            //fkColumnField = new JTextField(10);
            // 添加外键目标字段标签和输入框
            JLabel fkTargetColumnLabel = new JLabel("目标列:");
            //fkTargetColumnField = new JTextField(10);

            // 删除按钮
            JButton deleteButton = new JButton("删除");

            // 添加组件
            add(sourceLabel);
            add(sourceFieldComboBox);
            add(targetLabel);
            add(targetField);
            add(defaultLabel);  // 新增：添加默认值标签
            add(defaultValueField);  // 新增：添加默认值输入框
            add(typeLabel);
            add(conversionTypeComboBox);
            add(enumMappingButton);
            add(dateFormatLabel);
            add(dateFormatField);
            add(fkTableLabel);
            add(relationTableComboBox);
            add(fkColumnLabel);
            add(relationColumnComboBox);
            add(fkTargetColumnLabel);
            add(targetColumnComboBox);
            add(deleteButton);

            // 设置规则
            if (rule != null) {
                // 设置源字段
                for (int i = 0; i < sourceFieldComboBox.getItemCount(); i++) {
                    if (sourceFieldComboBox.getItemAt(i).equals(rule.getSourceField())) {
                        sourceFieldComboBox.setSelectedIndex(i);
                        break;
                    }
                }

                // 设置目标字段
                targetField.setText(rule.getTargetField());

                // 设置目标字段类型
                if (rule.getTargetType() != null) {
                    targetTypeLabel.setText("类型: " + rule.getTargetType());
                }

                if (rule.getDefaultValue() != null) {
                    defaultValueField.setText(rule.getDefaultValue());
                }

                // 设置转换类型
                conversionTypeComboBox.setSelectedItem(rule.getConversionType());

                // 设置日期格式
                dateFormatField.setText(rule.getDateFormat());

                if (rule.getForeignKeyTable() != null) {
                    for (int i = 0; i < relationTableComboBox.getItemCount(); i++) {
                        if (relationTableComboBox.getItemAt(i) != null && relationTableComboBox.getItemAt(i).equals(rule.getForeignKeyTable())) {
                            relationTableComboBox.setSelectedIndex(i);
                            break;
                        }
                    }
                }

                if (rule.getForeignKeyColumn() != null) {
                    for (int i = 0; i < relationColumnComboBox.getItemCount(); i++) {
                        if (relationColumnComboBox.getItemAt(i) != null && relationColumnComboBox.getItemAt(i).equals(rule.getForeignKeyColumn())) {
                            relationColumnComboBox.setSelectedIndex(i);
                            break;
                        }
                    }
                }

                if (rule.getForeignKeyTargetColumn() != null) {
                    for (int i = 0; i < targetColumnComboBox.getItemCount(); i++) {
                        if (targetColumnComboBox.getItemAt(i) != null && targetColumnComboBox.getItemAt(i).equals(rule.getForeignKeyTargetColumn())) {
                            targetColumnComboBox.setSelectedIndex(i);
                            break;
                        }
                    }
                }

                if (rule.getSourceField() != null) {
                    sourceFieldComboBox.addItem(rule.getSourceField());
                }

                // 更新枚举映射按钮状态
                //updateEnumMappingButtonState();
            }

            // 事件监听器
            //conversionTypeComboBox.addActionListener(e -> updateEnumMappingButtonState());
            enumMappingButton.addActionListener(e -> showEnumMappingDialog(rule));
            deleteButton.addActionListener(e -> {
                Container parent = this.getParent();
                if (parent != null && parent instanceof JPanel) {
                    JPanel panel = (JPanel) parent;
                    panel.remove(this);
                    panel.revalidate();
                    panel.repaint();
                }
            });
        }

        private void showEnumMappingDialog(MappingRule rule) {
            EnumMappingDialog dialog = new EnumMappingDialog((Frame) SwingUtilities.getWindowAncestor(this), "枚举映射配置", true, rule.getEnumMapping());
            dialog.setVisible(true);
            if (dialog.isConfirmed()) {
                rule.setEnumMapping(dialog.getMappingString());
                enumMappingValue = dialog.getMappingString();
            }
        }

//        private void updateEnumMappingButtonState() {
//            // 只有在枚举类型时才启用枚举映射按钮
//            Object selectedItem = conversionTypeComboBox.getSelectedItem();
//            if (selectedItem == null) {
//                enumMappingButton.setEnabled(false);
//                return;
//            }
//
//            boolean isEnum = !selectedItem.toString().equals("String");
//            enumMappingButton.setEnabled(isEnum);
//        }


        public MappingRule getMappingRule() {
            MappingRule rule = new MappingRule();
            rule.setSourceField((String) sourceFieldComboBox.getSelectedItem());
            rule.setTargetField(targetField.getText());
            // 设置目标字段类型
            rule.setTargetType(targetTypeLabel.getText().replace("类型: ", ""));
            rule.setConversionType((String) conversionTypeComboBox.getSelectedItem());
            rule.setDateFormat(dateFormatField.getText());
            if (relationTableComboBox.getSelectedItem() != null) {
                rule.setForeignKeyTable(relationTableComboBox.getSelectedItem().toString());
            }
            rule.setDefaultValue(defaultValueField.getText().isEmpty() ? null : defaultValueField.getText());
            if (relationColumnComboBox.getSelectedItem() != null) {
                rule.setForeignKeyColumn(relationColumnComboBox.getSelectedItem().toString());
            }
            if (targetColumnComboBox.getSelectedItem() != null) {
                rule.setForeignKeyTargetColumn(targetColumnComboBox.getSelectedItem().toString());
            }

            if (enumMappingButton.getText().equals("枚举映射")) {
                // 假设我们有一个方法来获取当前的枚举映射字符串
                rule.setEnumMapping(enumMappingValue);
            }
            return rule;
        }
    }

}
